package com.kevin.demo.framwork;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kevin.demo.enums.ResultEnum;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


/**
 * @author: e20160504
 * @date: 2018/8/29
 * @desc
 */
public class HttpClientUtil {

    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    /**
     * @params: url
     * @return: JSONObject
     * @desc: 无参数的http get请求
     */
    public static JSONObject doGet(String url, Map<String, Object> param) {

        JSONObject jsonObject = null;
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse httpresponse = null;
        try {
            //构造请求url
            URI requestUrl = getRequestUrl(url, param);
            //创建get请求
            HttpGet get = new HttpGet(requestUrl);
            get.addHeader("Content-Type", "application/json;charset=utf-8");

            httpresponse = client.execute(get);
            if (httpresponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                HttpEntity entity = httpresponse.getEntity();
                String response = EntityUtils.toString(entity);
                // 释放资源
                EntityUtils.consume(httpresponse.getEntity());
                jsonObject = JSON.parseObject(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpresponse != null) {
                    httpresponse.close();
                }
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    /**
     * @params: url
     * @return:
     * @desc: put方法调用
     */
    public static JSONObject doPut(String url, StringEntity param) {
        //获取httpClient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        String response = null;
        try {
            //创建put请求
            HttpPut httpPut = new HttpPut(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
            httpPut.setConfig(requestConfig);
            httpPut.setHeader("Content-Type", "application/json;charset=utf-8");
            //设置参数发送请求
            httpPut.setEntity(param);
            //得到相应信息
            httpResponse = httpClient.execute(httpPut);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                httpPut.abort();
                logger.error("请求" + ResultEnum.REQUEST_ERROR.getMsg() + "超时 url" + url);
            }

            HttpEntity entity = httpResponse.getEntity();
            response = EntityUtils.toString(entity, "UTF-8");
            //释放资源
            EntityUtils.consume(httpResponse.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (httpResponse != null) {
                    httpResponse.close();
                }
                httpClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return JSON.parseObject(response);

    }

    /**
     *@params: 请求参数是json格式
     *@return:
     *@desc: doPost 方法
     */
    public static JSONObject doPost(String url, StringEntity param){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse = null;
        JSONObject jsonObject = null;
        try {
            //创建post请求
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
            httpPost.setConfig(requestConfig);
            httpPost.setHeader("Accept", "application/json");
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            // 提交参数发送请求
            httpPost.setEntity(param);
            httpResponse = httpclient.execute(httpPost);
            // 得到响应信息
            HttpEntity entity = httpResponse.getEntity();
            String response = EntityUtils.toString(entity, "UTF-8");
            // 释放资源
            EntityUtils.consume(httpResponse.getEntity());
            jsonObject = JSON.parseObject(response);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try{
                if(httpResponse != null){
                    httpResponse.close();
                }
                httpclient.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return jsonObject;
    }

    //构造get请求url
    private static URI getRequestUrl(String url,Map<String,Object> param) throws Exception {
        URIBuilder builder = new URIBuilder(url);
        if (CollectionUtils.isEmpty(param)){
            for(String key : param.keySet()){
                builder.addParameter(key,String.valueOf(param.get(key)));
            }
        }
        return builder.build();

    }

    //将map转换为key=value格式
    private static StringEntity getEntityParam(Map<String,Object> param) throws UnsupportedEncodingException {
        StringEntity reqEntity = null;
        if(param == null){
            return reqEntity;
        }
        List<NameValuePair> paramList = new ArrayList<>();
        for(String key : param.keySet()){
            paramList.add(new BasicNameValuePair(key,String.valueOf(param.get(key))));
        }
        // 模拟表单
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
        return entity;
    }
}
